package cn.xuexiluxian.open.admin.controller.logger;

import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.annotation.RepeatSubmit;
import cn.xuexiluxian.open.common.enums.BusinessType;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.system.model.entity.SystemLoginLog;
import cn.xuexiluxian.open.system.model.req.LoginLogREQ;
import cn.xuexiluxian.open.system.service.ISystemLoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 登录日志
 */
@Slf4j
@RestController
@RequestMapping("logger/login")
public class LoginLoggerController {
    @Autowired
    private ISystemLoginLogService systemLoginLogService;

    @GetMapping(value = "/page")
    @Log(title = "登录日志", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('logger:login:page')")
    public ResponseResult page(Page page, LoginLogREQ loginLogREQ){
        Page<SystemLoginLog> pageList = systemLoginLogService.pageList(page, loginLogREQ);
        return ResponseResult.ok(pageList);
    }

    @GetMapping(value = "get/{id}")
    @Log(title = "登录日志", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('logger:login:get')")
    public ResponseResult get(@PathVariable String id) {
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemLoginLog systemLoginLog = systemLoginLogService.getById(id);
        if(systemLoginLog != null){
            return ResponseResult.ok(systemLoginLog);
        }
        return ResponseResult.error(ResultStatusCodeEnum.DATA_NO_EXIST);
    }

    @RepeatSubmit
    @PostMapping(value = "delete")
    @Log(title = "登录日志", businessType = BusinessType.DELETE)
    @PreAuthorize("@permission.hasPermission('logger:login:delete')")
    public ResponseResult del(@RequestBody List<String> ids){
        boolean b = systemLoginLogService.removeByIds(ids);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    @RepeatSubmit
    @GetMapping(value = "clean")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @PreAuthorize("@permission.hasPermission('logger:login:clean')")
    public ResponseResult clean(){
        boolean b = systemLoginLogService.clean();
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }
}
